<?php

use Carbon\Carbon;
class CustomValidator extends Illuminate\Validation\Validator {
	
	protected $implicitRules = array(
		'Required', 'RequiredWith', 'RequiredWithout', 'RequiredIf', 'Accepted', 'RequiredWithoutField',
		'Componentsrequired', 'Componentsnotempty', 'Before', "Alpha_spaces", "AccessoryCostsCentres", 'Componentsamount'
	);

	public function validateComponentsrequired($attribute, $value, $parameters = null) {
		if (empty($value)) {
			return false;
		}
		
		return true;
	}

    public function validateBigint($attribute, $value)
	{
		return is_numeric($value);
	}
	
	public function validateComponentsnotempty($attribute, $value, $parameters = null) {
		if (empty($value)) {
			// existencia é validada por componentsrequired
			return true;
		}
				
		if (is_array($value)) {
			foreach ($value as $item) {
				if (empty($item)) {
					return false;
				}
			}
		}
	
		return true;
	}
	
	public function validateComponentsamount($attribute, $value, $parameters = null) {
		if (empty($value)) {
			// existencia é validada por componentsrequired
			return true;
		}
	
		if (is_array($value)) {
			foreach ($value as $item) {
				if (!is_numeric($item)) {
					return false;
				}
			}
		}
	
		return true;
	}
	
	public function validateBeforecustom($attribute, $value, $parameters = null) {
		$start = Carbon::createFromFormat("d/m/Y", $value);
		
		if (empty($parameters[0])) {
			return false;
		}
		
		$end = Carbon::createFromFormat("d/m/Y", $parameters[0]);
		
		if ($start->gt($end)) {
			return false;
		}
		
		return true;
	}
	
	public function validateTotalcc($attribute, $value, $parameters = null) {
		if (is_array($value)) {
			foreach ($value as $item) {
				if (count(explode(',', $item)) > $parameters[0]) {
					return false;
				}
			} 
		}
		
		return true;
	}
	
	public function validateAlphaSpaces($attribute, $value, $parameters = null) {
		return preg_match('/^[\pL\s]+$/u', $value);
	}
	
	public function validateAccessoryCostsCentres($attribute, $value, $parameters) {
		
		if (is_array($value)) {
			foreach ($value as $key => $accessory) {
				if ($accessory == 1) {
					$strCostsCentres = $this->getValue($parameters[0]);
					$costsCentres = explode(",", $strCostsCentres[$key]);
					
					if (count($costsCentres) > 1) {
						return false;
					}
				}
			}
		}

		return true;
	}
}